﻿<%@ WebHandler Language="C#" Class="WorkShiftManageHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

//Description:班次维护处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-04-21
public class WorkShiftManageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    WorkShiftBusiness workshiftBusiness = new WorkShiftBusiness();
    LimitedCapacityBusiness limitBusiness = new LimitedCapacityBusiness();//排产类
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetWorkShiftDatas": //获取班次数据
                    GetWorkShiftDatas(context);
                    break;
                case "GetDetailInfo": //获取班次详细加工时间数据
                    GetDetailInfo(context);
                    break;
                case "GetAddWorkShiftDetail": //获取添加后的加工列表
                    GetAddWorkShiftDetail(context);
                    break;
                case "SaveWorkShiftDatas": //保存班次数据
                    SaveWorkShiftDatas(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 获取班次数据列表
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkShiftDatas(HttpContext context)
    {
        string workShiftName = context.Request["workShiftName"].ToString();
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("workShiftName", workShiftName);
        dic.Add("PageIndex", pageNumber);
        dic.Add("PageSize", pageSize);
        uMESProcessResult result = workshiftBusiness.GetWorkShiftListByPage(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取班次详细加工信息
    /// </summary>
    /// <param name="context"></param>
    public void GetDetailInfo(HttpContext context)
    {
        string workshiftId = context.Request["workshiftId"].ToString();
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result.DBTable = workshiftBusiness.GetWorkShiftDetailInfo(workshiftId);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 添加加工时间
    /// </summary>
    /// <param name="context"></param>
    public void GetAddWorkShiftDetail(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        // string workshiftId = context.Request["workshiftId"].ToString();
        string addStart = context.Request["startTime"].ToString();
        string addEnd = context.Request["endTime"].ToString();
        int mins = GetMins(addStart, addEnd);
        DataTable dtNew = new DataTable();
        if (dt.Rows.Count == 0)
        {
            dtNew.Columns.Add("WORKSHIFTDETAILID");
            dtNew.Columns.Add("WORKSHIFTID");
            dtNew.Columns.Add("STARTDATE");
            dtNew.Columns.Add("ENDDATE");
            dtNew.Columns.Add("SEQUENCE");
            dtNew.Columns.Add("MINS");
            DataRow dr = dtNew.NewRow();
            dr["WORKSHIFTDETAILID"] = "";
            dr["WORKSHIFTID"] = "";
            dr["STARTDATE"] = addStart;
            dr["ENDDATE"] = addEnd;
            dr["SEQUENCE"] = 1;
            dr["MINS"] = mins;
            dtNew.Rows.Add(dr);
        }
        else
        {
            dtNew = dt.Copy();
            dtNew.Rows.Clear();
            int st = int.Parse(addStart.Replace(":", ""));
            int et = int.Parse(addEnd.Replace(":", ""));
            bool isInsert = false;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow item = dt.Rows[i];
                if (isInsert)
                {
                    item["SEQUENCE"] = int.Parse(item["SEQUENCE"].ToString()) + 1;
                    dtNew.Rows.Add(item.ItemArray);
                    continue;
                }
                int ost = int.Parse(item["startDate"].ToString().Replace(":", ""));
                int oet = int.Parse(item["endDate"].ToString().Replace(":", ""));
                if (st >= ost && st <= oet)
                {
                    result.Result = false;
                    result.Message = "添加的开始时间无效";
                    break;
                }
                if (et >= ost && et <= oet)
                {
                    result.Result = false;
                    result.Message = "添加的结束时间无效";
                    break;
                }
                if (st <= ost && et >= oet && (ost < oet))
                {
                    result.Result = false;
                    result.Message = "添加的时间范围无效";
                    break;
                }
                if (st < ost)
                {
                    DataRow dr = dtNew.NewRow();
                    dr["WORKSHIFTDETAILID"] = "";
                    dr["WORKSHIFTID"] = "";
                    dr["STARTDATE"] = addStart;
                    dr["ENDDATE"] = addEnd;
                    dr["SEQUENCE"] = int.Parse(item["SEQUENCE"].ToString());
                    dr["MINS"] = mins;
                    dtNew.Rows.Add(dr);
                    isInsert = true;
                    item["SEQUENCE"] = int.Parse(item["SEQUENCE"].ToString()) + 1;
                    dtNew.Rows.Add(item.ItemArray);
                }
                else
                {
                    dtNew.Rows.Add(item.ItemArray);
                    if (st > oet && (i + 1) < dt.Rows.Count)
                    {
                        continue;
                    }
                    DataRow dr = dtNew.NewRow();
                    dr["WORKSHIFTDETAILID"] = "";
                    dr["WORKSHIFTID"] = "";
                    dr["STARTDATE"] = addStart;
                    dr["ENDDATE"] = addEnd;
                    dr["SEQUENCE"] = int.Parse(item["SEQUENCE"].ToString()) + 1;
                    dr["MINS"] = mins;
                    dtNew.Rows.Add(dr);
                    isInsert = true;
                }
            }
        }
        if (result.Result)
        {
            result.DBTable = dtNew;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取两个时间的分钟
    /// </summary>
    /// <param name="st"></param>
    /// <param name="et"></param>
    /// <returns></returns>
    private int GetMins(string st, string et)
    {
        DateTime start = DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd") + " " + st);
        DateTime end = DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd") + " " + et);
        if (start > end)//如果结束时间小于开始时间
        {
            end = end.AddDays(1);
        }
        return (int)limitBusiness.GetDifferMins(end, start);//获取时间段的分钟
    }

    /// <summary>
    /// 保存班次数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveWorkShiftDatas(HttpContext context)
    {
        DataTable dtMain = new DataTable();//班次主表信息
        DataTable dtDetail = new DataTable();//加工时间表
        dtMain = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtMain.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "没有需要保存的数据" }));
            return;
        }
        DataRow dr = dtMain.Rows[0];
        if (dr["type"].ToString() != "delete")
        {
            dtDetail = JsonConvert.DeserializeObject<DataTable>(context.Request["details"].ToString());
            if (dtDetail.Rows.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "没有需要保存的数据" }));
                return;
            }
        }
        uMESProcessResult result = new uMESProcessResult();
        result = workshiftBusiness.SaveWorkShiftData(dr, dtDetail, m_UserInfo.EmployeeID.ToString());
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
}